package com.bju.service.impl;

import com.bju.service.PassPortService;
import com.bju.utils.Base64Utils;
import okhttp3.*;
import org.json.JSONObject;
import org.springframework.stereotype.Service;

import java.io.*;

@Service
public class PassportServiceImpl implements PassPortService {
    public static final String API_KEY = "L3uZQMZmWsYzyGshGTgpAKSc";
    public static final String SECRET_KEY = "d4Gngofx7Fj3rVwmTenbaMOSXee40Wlk";
    static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();
    /**
     * 从用户的AK，SK生成鉴权签名（Access Token）
     *
     * @return 鉴权签名（Access Token）
     * @throws IOException IO异常
     */
    static String getAccessToken() throws IOException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + API_KEY
                + "&client_secret=" + SECRET_KEY);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token")
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        return new JSONObject(response.body().string()).getString("access_token");
    }

    /**
     * 获取图片返回信息
     * @param path
     * @return
     * @throws IOException
     */
    @Override
    public String getPassportMessage(String path) throws IOException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");

        String fileContentAsBase64 = Base64Utils.getFileContentAsBase64(path, true);
        RequestBody body = RequestBody.create(mediaType, "image=" + fileContentAsBase64);

        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rest/2.0/ocr/v1/passport?access_token=" + getAccessToken())
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .addHeader("Accept", "application/json")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();

        return response.body().string();
    }



}
